import React from 'react'
import {
  View,
  FlatList,
  Pressable,
  Text,
  StyleSheet
} from 'react-native'

import Card from '~/components/card/index'
import {rxPostHot} from '~/utils/api'

class Component extends React.Component {
  constructor (props) {
    super(props),

    this.state = {
      isLoading: false,
      // 当前页
      page: 1,
      // 是否已经到最后一页
      pageEnd: false,
      data: [],
    }
  }

  componentDidMount () {
    this.appendData({page: 1})
  }

  // append data
  appendData ({page=1}) {
    let { data, pageEnd } = this.state

    // console.debug("rxpostHost: 发送请求")
    rxPostHot({page: page}).then((response) => {
      // console.debug("rxpostHost: 收到数据")
      if (response.errno == 0) {

        // 第一页重置数据
        if (page == 1) {
          data = []
          pageEnd = false
        }

        // 是否是最后一页
        if (response.pageSize != response.data.length) {
          pageEnd = true
        }

        // set data
        this.setState({
          page: page,
          pageEnd: pageEnd,
          data: data.concat(response.data),
          isLoading: false,
        })

        // console.debug("rxpostHost: 设置数据")
      }
    })
  }

  // 下拉更新数据
  onRefresh () {
    this.appendData({page: 1})
  }

  // 上拉加载
  onAppend () {
    let { isLoading, page, pageEnd } = this.state

    // 防止重复请求
    if (pageEnd == false && isLoading != true) {
      this.setState({
        isLoading: true
      })

      this.appendData({page: page+1})
    }
  }

  render() {
    const { navigation } = this.props

    return (
      <View style={{flex: 1}}>
        <FlatList
          data = {this.state.data}
          renderItem = {(item) => this.renderItem(item, navigation)}
          keyExtractor = {(item, index)  => index.toString()}
          // 下啦刷新
          refreshing = {this.state.isLoading}
          onRefresh = { () => this.onRefresh() }
          // 加载更多
          onEndReached = { () => this.onAppend() }
          // 是否显示垂直滚动条
          showsVerticalScrollIndicator = {true}
          // 尾部组件
          ListFooterComponent = { () => this.renderFooter() }
        ></FlatList>
      </View>
    )
  }

  renderItem ({item}, navigation) {
    return (
      <Pressable onPress={ () => navigation.navigate('DiscussDetail', {data: item}) }>
        <Card data={item}></Card>
      </Pressable>
    )
  }

  renderFooter () {
    let { pageEnd } = this.state

    let load = <Text style={styles.footerText}>··· ···</Text>
    let end = <Text style={styles.footerText}>~~~~ 我们是有底线的 ~~~~</Text>

    return (
      <View style={styles.footer}>
        {pageEnd ? end : load}
      </View>
    )
  }
}

const styles = StyleSheet.create({
  footer: {
    flex: 1,
    padding: 30,
    alignItems: 'center',
    // backgroundColor: '#ccbbcc',
  },
  footerText: {
    color: '#A0AEC0',
  }
})

export default Component;
